from typing import List, Any

from django.db.models import QuerySet, Sum
from ninja.pagination import PaginationBase
from ninja import Schema, Field
from ninja.types import DictStrAny


class MyPagination(PaginationBase):
    class Input(Schema):
        pageSize: int = Field(10, gt=0)
        page: int = Field(1, gt=-1)

    class Output(Schema):
        page: int
        limit: int
        items: List[Any]
        total: int
        code: int = 0
        other: dict = {}

    def paginate_queryset(
            self,
            queryset: QuerySet,
            pagination: Input,
            **params: DictStrAny,
    ) -> Any:
        offset = pagination.pageSize * (pagination.page - 1)
        limit: int = pagination.pageSize
        result = {
            "page": offset,
            "limit": limit,
            "items": queryset[offset: offset + limit],
            "total": self._items_count(queryset),
            "code": 0,
            "other": {}
        }
        if params.get("serializer_class", None):
            serializer_class = params.get("serializer_class", None)
            result["items"] = serializer_class(result["items"], many=True).data
        if params.get("is_total", False):
            result["other"] = queryset.aggregate(number=Sum("number"))
        return result
